<?php

if (isset($_POST['reset'])) {
	
	if (isset($_POST['reset']['username'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND username=?", array($site['id'], $_POST['reset']['reminder']));
	} elseif(isset($_POST['reset']['email'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND email=?", array($site['id'], $_POST['reset']['email']));
	} elseif(isset($_POST['reset']['username_or_email'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND (username=? OR email=?)", array($site['id'], $_POST['reset']['username_or_email'], $_POST['reset']['username_or_email']));
	}
	
	if ($user) {
		$authkey = sha1(implode('', $user));
		if (isset($_POST['reset']['authkey'])) {
			if ($authkey == $_POST['reset']['authkey']) {
				$user = new User($user['id']);
				$user->user['password1'] = $_POST['reset']['password1'];
				$user->user['password2'] = $_POST['reset']['password2'];
				if ($user->save($errors)) {
					$smarty->assign('success', 'PASSWORDRESET');
				} else {
					$smarty->assign('errors', $errors);
				}
			} else {
				$smarty->append('errors', 'AUTHKEY');
			}
		} else {
			$smarty->assign('reset_url', 'http://' . $site['domain_name'] . ($page['full_path'] == '/' ? '' : $page['full_path']) . '/reset-password/?reset[authkey]=' . $authkey);
			$smarty->assign('reset_url_only', 'http://' . $site['domain_name'] . ($page['full_path'] == '/' ? '' : $page['full_path']) . '/reset-password/');
			$smarty->assign('site', $site);
			mail($user['email'], 'Password reset', $smarty->fetch('user/reset-password.tpl.text-email'), 'From: noreply@' . preg_replace("/^www\./", "", $site['domain_name']));
			$smarty->assign('success', 'MAILSENT');
		}
	} else {
		$smarty->append('errors', 'NOUSER');
	}
}

$smarty->display('user/reset-password.tpl.html');
